package jmine.tec.database.pack.populator;

import jmine.tec.database.pack.Pack;
import jmine.tec.database.pack.PackException;

/**
 * Populador abstrado de pacotes para implementações que se baseiam no formato de serviços.
 * 
 * @author lundberg
 * @param <T> tipo de objeto raiz da exportação
 */
public class DefaultPackPopulator<T> extends AbstractPackPopulator {

    private String fileCode;

    private PopulatorDataSource<T> dataSource;

    private PopulatorWriter<T> writer;

    /**
     * {@inheritDoc}
     */
    public final void populate(Pack pack) throws PackException {
        for (PopulatorBean<T> root : this.dataSource.load()) {
            this.addToPack(pack, root);
        }
    }

    /**
     * @param pack pack
     * @param root root
     * @throws PackException PackException
     */
    private void addToPack(Pack pack, PopulatorBean<T> root) throws PackException {
        this.writer.write(root.getSource(), pack.put(this.fileCode, root.getPath()));
    }

    /**
     * @param fileCode the fileCode to set
     */
    public void setFileCode(String fileCode) {
        this.fileCode = fileCode;
    }

    /**
     * @param dataSource the dataSource to set
     */
    public void setDataSource(PopulatorDataSource<T> dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * @param writer the writer to set
     */
    public void setWriter(PopulatorWriter<T> writer) {
        this.writer = writer;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean equals(Object obj) {
        if (!super.equals(obj)) {
            return false;
        }
        DefaultPackPopulator<?> o = (DefaultPackPopulator) obj;
        return this.dataSource.equals(o.dataSource) && this.writer.equals(o.writer);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = super.hashCode();
        result = prime * result + ((this.dataSource == null) ? 0 : this.dataSource.hashCode());
        result = prime * result + ((this.writer == null) ? 0 : this.writer.hashCode());
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return String.format("DefaultPackPopulator:[fileCode=%s,dataSource=%s,writer=%s]", this.fileCode, this.dataSource, this.writer);
    }
}
